# Redis Installer Script for Windows
# This script downloads and installs Redis on Windows

# Configuration
$downloadUrl = "https://github.com/microsoftarchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi"
$installerPath = "$env:TEMP\Redis-x64-3.0.504.msi"
$logFile = "redis_install_log.txt"

# Create log file or clear existing one
if (Test-Path $logFile) {
    Clear-Content $logFile
} else {
    New-Item -Path $logFile -ItemType File -Force | Out-Null
}

# Logging function
function Write-Log {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Message,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet("INFO", "WARNING", "ERROR")]
        [string]$Level = "INFO"
    )
    
    $time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "[$time] [$Level] $Message"
    
    # Output to console with color
    switch ($Level) {
        "INFO"    { Write-Host $logMessage -ForegroundColor White }
        "WARNING" { Write-Host $logMessage -ForegroundColor Yellow }
        "ERROR"   { Write-Host $logMessage -ForegroundColor Red }
    }
    
    # Write to log file
    Add-Content -Path $logFile -Value $logMessage
}

# Check if Redis is already installed
Write-Log "Checking if Redis is already installed..." "INFO"
$redisService = Get-Service -Name Redis -ErrorAction SilentlyContinue

if ($redisService) {
    Write-Log "Redis service is already installed" "INFO"
    
    if ($redisService.Status -eq "Running") {
        Write-Log "Redis service is running" "INFO"
    } else {
        Write-Log "Redis service is not running, attempting to start" "WARNING"
        try {
            Start-Service Redis
            Start-Sleep -Seconds 2
            $redisService.Refresh()
            if ($redisService.Status -eq "Running") {
                Write-Log "Redis service started successfully" "INFO"
            } else {
                Write-Log "Failed to start Redis service" "ERROR"
            }
        } catch {
            Write-Log "Error starting Redis service: $_" "ERROR"
        }
    }
    
    Write-Log "Redis installation check complete" "INFO"
    Write-Log "You can now run the backend services using english_start.ps1" "INFO"
    exit 0
}

# Check if Redis executable exists but not as a service
$redisExe = Get-Command redis-server -ErrorAction SilentlyContinue
if ($redisExe) {
    Write-Log "Redis executable found but not registered as a service" "WARNING"
    Write-Log "Attempting to register Redis as a service..." "INFO"
    
    try {
        Start-Process -FilePath "redis-server" -ArgumentList "--service-install" -Wait -NoNewWindow
        Start-Process -FilePath "redis-server" -ArgumentList "--service-start" -Wait -NoNewWindow
        
        # Check if service was registered successfully
        $redisService = Get-Service -Name Redis -ErrorAction SilentlyContinue
        if ($redisService) {
            Write-Log "Redis service registered and started successfully" "INFO"
            Write-Log "You can now run the backend services using english_start.ps1" "INFO"
            exit 0
        } else {
            Write-Log "Failed to register Redis as a service" "ERROR"
        }
    } catch {
        Write-Log "Error registering Redis as a service: $_" "ERROR"
    }
}

# Download and install Redis
Write-Log "Redis is not installed. Starting installation..." "INFO"

# Check if running as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Log "This script requires administrator privileges to install Redis" "ERROR"
    Write-Log "Please restart this script as an administrator" "ERROR"
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Gray
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

# Download Redis installer
Write-Log "Downloading Redis installer from $downloadUrl" "INFO"
try {
    Invoke-WebRequest -Uri $downloadUrl -OutFile $installerPath
    Write-Log "Download completed successfully" "INFO"
} catch {
    Write-Log "Failed to download Redis installer: $_" "ERROR"
    exit 1
}

# Install Redis
Write-Log "Installing Redis..." "INFO"
try {
    $process = Start-Process -FilePath "msiexec.exe" -ArgumentList "/i `"$installerPath`" /qn" -Wait -PassThru
    
    if ($process.ExitCode -eq 0) {
        Write-Log "Redis installed successfully" "INFO"
    } else {
        Write-Log "Redis installation failed with exit code: $($process.ExitCode)" "ERROR"
        exit 1
    }
} catch {
    Write-Log "Error during Redis installation: $_" "ERROR"
    exit 1
}

# Verify Redis service is installed
Write-Log "Verifying Redis service..." "INFO"
$redisService = Get-Service -Name Redis -ErrorAction SilentlyContinue

if ($redisService) {
    Write-Log "Redis service installed successfully" "INFO"
    
    # Start Redis service
    Write-Log "Starting Redis service..." "INFO"
    try {
        Start-Service Redis
        Start-Sleep -Seconds 2
        $redisService.Refresh()
        
        if ($redisService.Status -eq "Running") {
            Write-Log "Redis service started successfully" "INFO"
        } else {
            Write-Log "Failed to start Redis service" "ERROR"
        }
    } catch {
        Write-Log "Error starting Redis service: $_" "ERROR"
    }
} else {
    Write-Log "Redis service not found after installation" "ERROR"
    Write-Log "Installation may have failed or service was not registered correctly" "ERROR"
    exit 1
}

# Cleanup
Write-Log "Cleaning up temporary files..." "INFO"
Remove-Item -Path $installerPath -Force -ErrorAction SilentlyContinue

Write-Log "Redis installation completed" "INFO"
Write-Log "You can now run the backend services using english_start.ps1" "INFO"

Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")